package com.zuihai.app.mvp.ui.activity.home;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.zuihai.app.R;
import com.zuihai.app.di.component.DaggerHomeRecyclerComponent;
import com.zuihai.app.di.module.HomeRecyclerModule;
import com.zuihai.app.mvp.constant.DetailConstant;
import com.zuihai.app.mvp.constant.HomeConstant;
import com.zuihai.app.mvp.contract.HomeRecyclerContract;
import com.zuihai.app.mvp.model.entity.HomeBanner;
import com.zuihai.app.mvp.model.entity.HomeItem;
import com.zuihai.app.mvp.presenter.HomeRecyclerPresenter;
import com.zuihai.app.mvp.ui.activity.detail.DetailContainerActivity;
import com.zuihai.app.mvp.ui.adapter.HomeRecyclerAdapter;
import com.zuihai.app.mvp.ui.widget.MyToast;
import com.zuihai.app.mvp.ui.widget.SimpleLoadMore;
import com.zuihai.app.mvp.ui.widget.SimpleRefresh;
import com.zuihai.app.mvp.ui.widget.behavior.listener.IsChildScrollListener;
import com.zuihai.app.mvp.ui.widget.behavior.listener.NeedExpandListener;
import com.zuihai.app.mvp.ui.widget.behavior.listener.SupportNeedExpendListener;
import com.zuihai.app.mvp.ui.utils.DividerListItemDecoration;


import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2017/5/4 0004.
 */

public abstract class HomeRecyclerFragment extends
        BaseFragment<HomeRecyclerPresenter> implements
        HomeRecyclerContract.View, BaseQuickAdapter.OnItemClickListener,
        SupportNeedExpendListener, IsChildScrollListener {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    @BindView(R.id.refresh_layout)
    TwinklingRefreshLayout mRefreshLayout;
    NeedExpandListener mNeedExpandListener;

    //加载更多监听
    protected BaseQuickAdapter.RequestLoadMoreListener mLoadMoreListener = new BaseQuickAdapter.RequestLoadMoreListener() {
        @Override
        public void onLoadMoreRequested() {
            requestData(false);
        }
    };

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeRecyclerComponent
                .builder()
                .appComponent(appComponent)
                .homeRecyclerModule(new HomeRecyclerModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_home_recycler, container, false);
    }

    @Override
    protected void initData() {
        initRefreshLayout();
        mRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.startRefresh();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    /**
     * 初始化下拉刷新
     */
    private void initRefreshLayout() {
        mRefreshLayout.setHeaderView(new SimpleRefresh(getContext()));
        mRefreshLayout.setEnableOverScroll(false);
        mRefreshLayout.setEnableLoadmore(false);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                requestData(true);
            }
        });
    }

    @Override
    public void setNeedExpendListener(NeedExpandListener listener) {
        mNeedExpandListener = listener;
    }

    @Override
    public NeedExpandListener getNeedExpendListener() {
        return mNeedExpandListener;
    }

    @Override
    public boolean childScroll(boolean mUp, boolean refresnEnable) {
        mRefreshLayout.setEnableRefresh(refresnEnable);
        RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
        return adapter != null && adapter.getItemCount() > 0 && ((LinearLayoutManager) mRecyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition() != 0;
    }

    /**
     * 不同类型请求不同数据
     */
    protected abstract void requestData(boolean isRefresh);

    @Override
    public void bindAdapter(HomeRecyclerAdapter adapter) {
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.layout_margtop_five,null);
        //添加条目点击事件
        adapter.setOnItemClickListener(this);
       // adapter.addHeaderView(view);
        //设置加载更多
        adapter.setOnLoadMoreListener(mLoadMoreListener, mRecyclerView);
        adapter.openLoadAnimation();
        adapter.setLoadMoreView(new SimpleLoadMore());
        mRecyclerView.setAdapter(adapter);

        //添加布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        //添加分割线
        DividerListItemDecoration decoration = new DividerListItemDecoration(getContext(), LinearLayoutManager.VERTICAL, R.drawable.common_divider_padding14_shape);
       //DividerNewDecoration decoration=new DividerNewDecoration(getContext(),LinearLayoutManager.VERTICAL);
       // Drawable mDrawable = ContextCompat.getDrawable(getActivity().getApplicationContext(), R.drawable.common_divider_padding14_shape);

        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                recyclerView.getAdapter().notifyDataSetChanged();
                if (mNeedExpandListener != null && dy < 0 && ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition() == 0) {
                    mNeedExpandListener.needExpand();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }

    public static final int MIN_CLICK_DELAY_TIME = 1000;
    public long lastClickTime = 0;
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        HomeItem item = (HomeItem) adapter.getItem(position);
        String detailId = item.id;
        switch (item.getItemType()) {
            case HomeConstant.ONE_TYPE:
            case HomeConstant.TWO_TYPE:
                DetailContainerActivity.launchActivity(getContext(), DetailConstant.HEADLINE_TYPE, detailId);
                break;
            case HomeConstant.THREE_TYPE:
                DetailContainerActivity.launchActivity(getContext(), DetailConstant.PICTURE_TYPE, detailId);
                break;
            case HomeConstant.FOUR_TYPE:
                switch (item.adType) {
                    case 1: //今日头条 酒城日记
                        DetailContainerActivity.launchActivity(getContext(), DetailConstant.HEADLINE_TYPE, detailId);
                        break;
                    case 2: // 发现秘密
                        DetailContainerActivity.launchActivity(getContext(), DetailConstant.SECRET_TYPE, detailId);
                        break;
                    case 3: // 有去除
                        DetailContainerActivity.launchActivity(getContext(), DetailConstant.SHOP_TYPE, detailId);
                        break;
                    case 4: // 逛街 (物品/服务)
                        DetailContainerActivity.launchActivity(getContext(), DetailConstant.COMMODITY_TYPE, detailId, item.commodityType);
                        break;
                }
                break;
        }
    }

    @Override
    public void setData(Object data) {

    }

    @Override
    public void handleError(Throwable e) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {
        mRefreshLayout.finishRefreshing();
    }

    @Override
    public void showMessage(String message) {
        if (!TextUtils.isEmpty(message)) {
            MyToast.showSuccess(message);
        }
    }

    @Override
    public void fillBanner(HomeRecyclerAdapter adapter, List<HomeBanner> banners) {
    }
}